package com.tsy.server.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tsy.server.common.page.ResultCode;
import com.tsy.server.system.entity.Organization;
import com.tsy.server.system.entity.User;
import com.tsy.server.system.mapper.OrganizationMapper;
import com.tsy.server.system.mapper.UserMapper;
import com.tsy.server.component.security.CustomUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Spring Security用户详情服务实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));

        if (user == null) {
            throw new RuntimeException(ResultCode.USERNAME_NOT_EXISTS.getMessage());
        }

        // 判断用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException(ResultCode.ACCOUNT_DISABLED.getMessage());
        }

        // 查询用户角色权限
        String roleKey = userMapper.getUserCurrentOrgRoleKey(user.getId(), user.getCurrentOrgId());
        if (roleKey == null) {
            roleKey = "default";
        }

        // 查询用户当前组织ID/workSpaceId
        Long orgId = user.getCurrentOrgId();
        Organization organization = organizationMapper.selectById(orgId);
        String workspaceId = organization.getOrgId();
        return new CustomUserDetails(user, roleKey, workspaceId);
    }
}